package com.keon.jianbao.adapter;

import android.view.View;
import android.view.ViewGroup;

import com.keon.jianbao.AppContext;
import com.keon.jianbao.AppManager;
import com.keon.jianbao.R;
import com.keon.jianbao.api.Api;
import com.keon.jianbao.base.BaseActivity;
import com.keon.jianbao.base.BaseListAdapter;
import com.keon.jianbao.bean.Msg;
import com.keon.jianbao.bean.Result;
import com.keon.jianbao.ui.widget.ItemLayout;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by keon on 2015/9/8.
 */
public class MessageListAdapter extends BaseListAdapter {

    AsyncHttpResponseHandler readHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            try {
                Result result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    BaseActivity baseActivity = (BaseActivity) AppManager.getAppManager().currentActivity();
                    baseActivity.showToast("置为已读");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            BaseActivity baseActivity = (BaseActivity) AppManager.getAppManager().currentActivity();
            baseActivity.showToast(R.string.common_error_network);
        }
    };

    static class ViewHolder {

        @Bind(R.id.message_item)
        ItemLayout ilMessage;

        public ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    @Override
    protected View getRealView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh = null;
        if (convertView == null || convertView.getTag() == null) {
            convertView = getLayoutInflater(parent.getContext()).inflate(
                    R.layout.list_cell_message, null);
            vh = new ViewHolder(convertView);
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }

        final Msg msg = (Msg) mDatas.get(position);

        vh.ilMessage.setTitle(msg.getMessage());
        vh.ilMessage.setSummary(msg.getCreate_time());
        if (msg.getUnread() != 0) {
            vh.ilMessage.showBadge(View.VISIBLE);
            final ViewHolder finalVh = vh;
            vh.ilMessage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Api.msg_do_read(msg.getId(), readHandler);
                    finalVh.ilMessage.showBadge(View.GONE);
                }
            });
        }

        return convertView;
    }
}
